package com.ajax.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QueryParseException;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;

import virtuoso.jena.driver.VirtGraph;
import virtuoso.jena.driver.VirtuosoQueryExecution;
import virtuoso.jena.driver.VirtuosoQueryExecutionFactory;

/**
 * Servlet implementation class BMapServlet
 */
public class BMapServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
  
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8"); 
		response.setContentType("text/html");
		
		String url,json="";
		url = "jdbc:virtuoso://localhost/:1111/charset=UTF-8/log_enable=2";
		VirtGraph graph = new VirtGraph ("http://wust.edu.cn/Emergency",url, "dba", "dba");
		try{	Query sparql = QueryFactory.create("PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n "
				+ "PREFIX Property:<http://www.wust.edu.cn/emergency/property#>\n"
				+ "PREFIX Emr:<http://www.wust.edu.cn/emergency/>\n"
				+ "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>\n"+
				"PREFIX owl:<http://www.w3.org/2002/07/owl#>\n"
				+ "SELECT ?x ?t WHERE{?x Property:nation Emr:中国 . ?x Property:location ?t.}");
		VirtuosoQueryExecution vqe = VirtuosoQueryExecutionFactory.create (sparql, graph);
		ResultSet results = vqe.execSelect();
		List<String> r = results.getResultVars();
		json = "[";
	//	json+="{\"H0\":"+"\""+r.get(0)+"\",\"H1\":"+"\""+r.get(1)+"\"},";
		int j=0;
		while (results.hasNext()) {
			QuerySolution result = results.nextSolution();
			json+="{\""+r.get(0).toString()+"\":"+"\""+result.get(r.get(0).toString()).toString().substring(33)
					+"\",\""+r.get(1).toString()+"\":"+"\""+result.get(r.get(1).toString()).toString().substring(33)+"\"},\n";

		j++;
		}
		if(j!=0){
			//String json1 = "abcde";
			json=json.substring(0, json.length()-2);
			json+="]";
			}
			else{
				json+="]";
			}
		//System.out.println(json);
		vqe.close();
		}catch(QueryParseException e){
			json = "fail";
			System.out.println(e.getMessage());
		}
		PrintWriter out = response.getWriter();
		out.println(json);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("utf-8");
	
			
			this.doGet(request, response);
	}

}
